package czc.hly.spring.formework.context.support;

import czc.hly.spring.formework.beans.BeanDefinition;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;


//用来对配置文件进行查找（定位），读取，解析
public class BeanDefinitionReader {

    private Properties config = new Properties();

    private List<String> registyBeanClasses = new ArrayList<String>();

    //在配置文件中，用来获取自动扫描的包名的KEY
    private final String SCAN_PACKAGE = "scanPackage";

    public BeanDefinitionReader(String ... locations){
        //定位到resource下的properties文件
        InputStream is = this.getClass().getClassLoader().getResourceAsStream(locations[0].replace("classpath:",""));
        try {
            //载入Properties对象里
            config.load(is);
            System.out.println("BeanDefinitionReader的config属性值为:"+config);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (is != null){
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        doScanner(config.getProperty(SCAN_PACKAGE));
    }

    public List<String> loadBeanDefinitions(){
        return registyBeanClasses;
    }

    //每注册一个className，就返回一个BeanDefinition（自己包装）
    //只是为了对配置信息进行一个包装
    public BeanDefinition registerBean(String className){
        if (this.registyBeanClasses.contains(className)){
            BeanDefinition beanDefinition = new BeanDefinition();
            beanDefinition.setBeanClassName(className);
            beanDefinition.setFactoryBeanName(lowerFirstCase(className.substring(className.lastIndexOf(".")+1)));
            return beanDefinition;
        }
        return null;
    }

    public Properties getConfig(){
        return this.config;
    }

    //加载
    //递归扫描所有相关联的class，并且保存到一个List中
    private void doScanner(String packageName){
        //XXXX绝对路径定位资源
        File classDir = new File("C:\\Program Files\\Apache Software Foundation\\Tomcat 8.0\\webapps\\ROOT\\WEB-INF\\classes\\"+packageName.replaceAll("\\.","/"));
        //获取文件数组
        File[] files = classDir.listFiles();
        for (File file : files){
            if(file.isDirectory()){
                //如果是文件夹-》加上文件夹名进行递归调用doScanner方法
                doScanner(packageName + "." +file.getName());
            }else {
                //如果不是文件夹-》去掉.class后缀加入到集合
                registyBeanClasses.add(packageName + "." + file.getName().replace(".class",""));
            }
        }

        System.out.println(registyBeanClasses);


    }



    //把String的首字母变成小写
    private String lowerFirstCase(String str){
        char [] chars = str.toCharArray();
        chars[0] += 32;
        return String.valueOf(chars);
    }

}
